package org.alvin.bolai;

import io.netty.buffer.ByteBufUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

public class BolaiClient {

    static JTextArea txtSend = new JTextArea();
    static JTextArea txtConsole = new JTextArea();

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 10008); // 10010
        new Thread() {
            @Override
            public void run() {
                try (InputStream in = socket.getInputStream()) {
                    byte[] buff = new byte[2048];
                    int len;
                    while ((len = in.read(buff)) > 0) {
                        byte[] data = new byte[len];
                        System.arraycopy(buff, 0, data, 0, data.length);
                        System.out.println(ByteBufUtil.hexDump(data));
                        txtConsole.append("接收到数据：\n");
                        txtConsole.append(ByteBufUtil.hexDump(data));
                        txtConsole.append("\n");
                        txtConsole.append(ByteBufUtil.hexDump(data));
//                            data  =   parseData(data, socket);
//                            if(data.length <= 4){
//                                break;
//                            }
//                            System.out.printf("继续解析----");

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
//        new Thread() {
//            @Override
//            public void run() {
////                while (true) {
//                    try {
//                        TimeUnit.SECONDS.sleep(2);
//                        txtConsole.append("发送心跳\n");
//                        String text = "fcfe005104010110010a010200000000000000000801034740329010810a01043138372e312e30320301051f1601483839383630344434313732324430343933303736040201974e040201980f0402019903f5fcee";
//                        byte[] buff = ByteUtils.hexString2Bytes(text);
//                        try {
//                            socket.getOutputStream().write(buff);
//                            socket.getOutputStream().flush();
//                            System.out.println("--------------执行心跳发送");
//                        } catch (IOException ex) {
//                            throw new RuntimeException(ex);
//                        }
//                        TimeUnit.SECONDS.sleep(10);
//                    } catch (InterruptedException e) {
//                        throw new RuntimeException(e);
//                    }
////                }
//            }
//        }.start();

        toShowUi(socket);
    }

    private static ByteArrayOutputStream tmpArray = new ByteArrayOutputStream();

//    private static byte[]  parseData(byte[] inData, Socket socket) throws IOException {
//        tmpArray.write(inData);
//        byte[] buff = tmpArray.toByteArray();
//        int sizes = buff.length;
//        if (sizes <= 4) {
//            return buff;
//        }
//        int index = 0;
//        int start1 = buff[0];
//        index++;
//        int start2 = buff[1];
//        index++;
//        //上行帧头
//        if (start1 != (byte) 0xFC || start2 != (byte) 0xFF) {
//            tmpArray.reset();
//            return buff;
//        }
//        //获取长度
//        int length = ByteUtils.bytes2ToIntHL(new byte[]{buff[2], buff[3]});
//        if (length > buff.length) {
//            tmpArray.reset();
//            return buff;
//        }
//        index += 2;
//        //消息体 去掉校验位和帧长，获取数据
//        byte[] data = new byte[length - 3];
//        System.arraycopy(buff, 4, data, 0, data.length);
//        //校验和
//        index += data.length;
//        System.out.println(index);
//        int checkSum = Integer.valueOf(ByteBufUtil.hexDump(new byte[]{buff[index]}), 16);
//        index++;
//        //校验和
//        byte[] checkSumBuff = new byte[length-1];
//        System.arraycopy(buff, 2, checkSumBuff, 0, checkSumBuff.length);
//        //尾帧
//        byte[] end = new byte[2];
//        System.arraycopy(buff, index, end, 0, end.length);
//        index +=2;
//        //判断尾帧 ，判断校验和
//        // 尾帧暂时忽略
//        // 判断校验和
//
//        int compare = ByteUtils.sumCheck(checkSumBuff);
//        if (compare != checkSum) {
//            txtConsole.append("报文检验不通过，报文校验值:" + checkSum + ",后台计算值：" + compare + "\n");
//            tmpArray.reset();
//            data = new byte[buff.length - 2];
//            System.arraycopy(buff, 2, data, 0, data.length);
//            return data;
//        }else {
//            tmpArray.reset();
//            int len =buff.length - index;
//            if(len > 0) {
//                data = new byte[buff.length - index];
//                System.arraycopy(buff, index, data, 0, data.length);
//                txtConsole.append("报文正常解析\n");
//                return data;
//            }else {
//                txtConsole.append("报文正常解析\n");
//                return new byte [0];
//            }
//        }
//    }

    private static void toShowUi(Socket socket) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout());

        txtConsole.setLineWrap(true);
        txtConsole.setPreferredSize(new Dimension(100, 300));
        frame.getContentPane().add(new JScrollPane(txtConsole), BorderLayout.CENTER);

        JPanel panel = new JPanel();

        panel.setLayout(new BorderLayout());

        panel.setBackground(Color.red);
        frame.getContentPane().add(panel, BorderLayout.SOUTH);


        txtSend.setPreferredSize(new Dimension(100, 300));
        txtConsole.setLineWrap(true);
        panel.add(new JScrollPane(txtSend), BorderLayout.CENTER);

        JPanel toolPanel = new JPanel();
        FlowLayout flowLayout = new FlowLayout(FlowLayout.RIGHT);
        toolPanel.setLayout(flowLayout);

        JButton button = new JButton("Send");

        toolPanel.add(button);

        panel.add(toolPanel, BorderLayout.NORTH);

        frame.setSize(1024, 768);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String text = txtSend.getText().trim().replaceAll("\r|\n|\r\n|\t", "");
                byte[] buff = ByteUtils.hexString2Bytes(text);
                try {
                    socket.getOutputStream().write(buff);
                    socket.getOutputStream().flush();
                    txtSend.setText("");
                    System.out.println("--------------发送调用完成");
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }

            }
        });

    }
}
